define(function(require, exports){
	var $ = require('jquery');
	var pubjs = require('pubjs');
	var view  = require('@base/view');
	var popwin	= require('@base/dialog');
	var drop = require('@base/common/drop');
	var input = require('@base/common/input');
	var grid  = require('@base/grid');
	var util  = require('util');

	// 创建新条件 模块
	var AddCondition = view.container.extend({
		init: function( config ) {
			config = pubjs.conf( config, {
				'class': 'P-adminSmartMonitorAddCondition',
				'max': 5,
				'dim': '',
				'timeOptions': [],
				'metricOptions': [],
				'operatorOptions': pubjs.config('smartMonitorOperator')
			});

			this.$conditionData = []; // 条件数据集合
			this.$index = 0;
			this.$unit = LANG('元');

			this.Super('init', arguments);
		},
		afterBuild: function(){
			var self = this;
			var el = self.getDOM();

			$([
				'<div class="conditionCon"/>',
				'<div class="addBtn link mt20 dib">'+LANG('添加条件')+'</div>'
			].join('')).appendTo(el);

			self.uiBind(el.find('>.addBtn'), 'click', 'eventAddItem');
			self.uiProxy(el, '.remove', 'click', 'eventRemoveItem');
		},
		buildItem: function(data){
			var self = this;
			var c = self.getConfig();
			var el = self.getDOM();

			if(self.$conditionData.length >= c.max){
				pubjs.alert(LANG('已达到条件的最大数量！'));
				return;
			}

			var index = self.$index++;
			var item = $([
				'<div class="item mt30">',
					'<div class="line">',
						'<span>'+LANG('且')+'</span>',
					'</div>',
					'<span>'+c.dim+'</span>',
					'<div class="dib con"></div>',
					'<div class="dib unit">' + self.$unit + '</div>',
					'<div class="dib valign-m">',
						'<i class="add icon-add dn"/>',
						'<i class="remove icon-close cur_p ml20"/>',
					'</div>',
				'</div>'
			].join('')).appendTo(el.find('.conditionCon'));

			// 时间
			var time = self.create('time_'+index, drop.drop, {
				'addClass': 'ml10 mr10',
				'options': c.timeOptions,
				'hasSearch': false,
				'width': 120,
				'value': 0,
				'target': item.find('.con')
			});
			// 指标
			var metric = self.create('metric_'+index, drop.drop, {
				'addClass': 'mr10',
				'options': c.metricOptions,
				'name': 'Name',
				'key': '_id',
				'width': 120,
				'value': 'cost',
				'target': item.find('.con'),
				'hasSearch': false,
				'panel_config': {
					'height': 150,
					'width': 200
				}
			});
			// 比较符
			var operator = self.create('operator_'+index, drop.drop, {
				'addClass': 'mr10',
				'options': c.operatorOptions,
				'hasSearch': false,
				'name': 'Name',
				'key': '_id',
				'width': 120,
				'value': '>=',
				'target': item.find('.con')
			});
			// 值
			var val = self.create('val_'+index, input.text, {
				'class': 'mr10',
				'width': 80,
				'value': 0,
				'placeholder': 0,
				'target': item.find('.con')
			}).setValue(0);

			// 如果有值，设置值
			if(data){
				time.setValue(data.IsAll === true ? 1 : 0),
				metric.setValue(data.Name);
				operator.setValue(data.Comparison);
				var value = data.Value || 0;
				// %为单位的，需要转换
				if(util.find(c.metricOptions, data.Name, '_id').NeedTrans){
					value = value*100;
				}
				val.setValue(value);
			}

			// 将每一个item，push到集合中
			self.$conditionData.push({
				'index': index,
				'modules': [time, metric, operator, val],
				'time': time,
				'metric': metric,
				'operator': operator,
				'val': val,
				'con': item,
				'unit': item.find('.unit'),
				'remove': item.find('.remove').attr('data-index', index)
			});

		},
		onDropChange: function(ev){
			var self = this;
			var index = ev.name.split('_')[1];
			var item = util.find(self.$conditionData, index, 'index');
			// 更改单位
			if(item){
				item.unit.text(ev.param.option.Unit);
			}
			return false;
		},
		eventAddItem: function(evt, elm){
			var self = this;
			self.buildItem();
			return false;
		},
		eventRemoveItem: function(evt, elm){
			var self = this;
			var index = $(elm).attr('data-index');
			self.removeItem(index);
			return false;
		},
		// 移除单个item
		removeItem: function(index){
			var self = this;
			var item = util.find(self.$conditionData, index, 'index');
			if(item){
				util.each(item.modules, function(module){
					if(module){
						module.destroy();
					}
				});
				item.con.remove();
				util.remove(self.$conditionData, index, 'index');
			}

			return self;
		},
		setData: function(data){
			if(data){
				var self = this;
				self.reset();
				util.each(data, function(item){
					if(item){
						self.buildItem(item);
					}
				});
			}
		},
		getData: function(){
			var self = this;
			var c = self.getConfig();
			var metricOptions = c.metricOptions;
			var conditionData = self.$conditionData;
			var data = [];

			util.each(conditionData, function(item){
				if(item){
					var name = item.metric.getValue(true).id;
					var value = Math.round(+item.val.getValue()*100)/100;
					// %为单位的，需要转换
					if(util.find(metricOptions, name, '_id').NeedTrans){
						value = value/100;
					}

					data.push({
						'Comparison': item.operator.getValue(true).id,
						'IsAll': Boolean(+item.time.getValue(true).id),
						'Name': name,
						'Value': value
					});
				}
			});

			return data;
		},
		reset: function(buildOne){
			var self = this;
			var conditionData = self.$conditionData;
			var i = 0;

			// 循环销毁模块
			while (i <= conditionData.length){
				if(!conditionData.length){
					break;
				}
				self.removeItem(conditionData[i].index);
			}

			self.$index = 0;

			// 如果有buildOne标识，默认构建一个item
			if(buildOne){
				self.buildItem();
			}
			return self;
		}
	});
	exports.addCondition = AddCondition;

	// 创建新条件 弹窗
	var CreateNew = popwin.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'size': 'm',
				'title': LANG('创建新条件')
			});

			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			self.Super('afterBuild', arguments);

			var el = self.getDOM('body');
			$([
				'<div class="M-formConGroup">',
					'<label class="group-label">'+LANG('监控维度：')+'</label>',
					'<div class="group-content">',
						'<span pub-name="dimType" pub-mod="@base/common/input.radio"></span>',
						'<div class="mt10 mb20">',
							LANG('为了得到更精确的监控效果，您可以同时设置基础指标和效果指标。'),
						'</div>',
						'<div class="condition">',
							'<div data-index="1"></div>',
							'<div data-index="2"></div>',
						'</div>',
					'</div>',
				'</div>'
			].join('')).appendTo(el);

			var config = {
				'dimType': {
					'data': [
						{'text': LANG('活动'), 'id':1, 'value':'campaign', 'checked': true},
						{'text': LANG('广告位'), 'id':2, 'value':'spot'}
					],
					'changeEvent': true
				}
			}

			// 活动的条件
			self.create('condition_1', AddCondition, {
				'target': el.find('.condition>div[data-index="1"]'),
				'dim': LANG('活动'),
				'timeOptions': [
					{'name': LANG('当日'), 'id': 0},
					{'name': LANG('最近30天'), 'id': 1}
				],
				'metricOptions': pubjs.config('smartMonitorMetric')['1']
			});

			// 广告位的条件
			self.create('condition_2', AddCondition, {
				'target': el.find('.condition>div[data-index="2"]').hide(),
				'dim': LANG('广告位'),
				'timeOptions': [
					{'name': LANG('当日'), 'id': 0}
				],
				'metricOptions': pubjs.config('smartMonitorMetric')['2']
			});

			self.buildFromTemplate(config);

		},
		afterBuildTemplate: function(ev){
			// 禁用维度, 只作显示用
			if(this.get('dimType')){
				this.get('dimType').disableAll(true);
			}
		},
		onRadioChange: function(ev){
			// 切换活动或广告位内容
			if(ev.name == 'dimType'){
				// var el = this.getDOM();
				// var cons = el.find('.condition>div').hide();
				// var id = ev.param.id;
				// cons.filter('[data-index="'+id+'"]').show();
			}
			return false;
		},
		onOk: function(ev){
			var self = this;
			var dimTypeData = self.$.dimType.getData(true);
			var id = dimTypeData.id;
			var data = self.get('condition_'+id).getData();

			var err = false;
			util.each(data, function(item){
				if(item){
					if(!util.isNumber(item['Value'])){
						err = true;
						return;
					}
				}
			});
			if(err){
				pubjs.alert(LANG('数值请填写大于等于0的数值。'));
				return false;
			}

			self.fire('addConditionSelected', data)
			self.hide();
			return false;
		},
		// 设置维度
		setDimType: function(dimType){
			this.$.dimType.setData(dimType);
			var cons = this.getDOM().find('.condition>div').hide();
			cons.filter('[data-index="'+dimType+'"]').show();
			return this;
		},
		setData: function(data){
			var self = this;
			if(data){
				// 更新标题
				self.setTitle(LANG('编辑条件'));
				var dimType = data.DimType;
				// 更新维度
				// if(self.get('dimType')){
				// 	self.get('dimType').setData(dimType);
				// }
				// 更新维度显隐
				self.setDimType(dimType);
				// 更新条件
				if(self.get('condition_' + dimType)){
					self.get('condition_' + dimType).setData(data.Conditions);
				}
			}
			return self;
		},
		reset: function(){
			var self = this;
			self.setTitle(self.getConfig('title'));
			if(self.get('dimType')){
				self.get('dimType').setData(1);
			}
			for(var i=1; i<3; i++){
				if(self.get('condition_'+i)){
					self.get('condition_'+i).reset('buildOne');
				}
			}
			return self;
		}
	});
	exports.createNew = CreateNew;

	var SelectAder = popwin.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'class': "M-aderSelector",
				'size': 'm',
				'title': LANG('广告主选择'),
				'data': null, // 选中的选项
			});

			this.$data = {};
			this.$selectedIds = [];
			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			self.Super('afterBuild', arguments);

			var el = self.getDOM('body');
			var c = self.getConfig();

			el.append($([
				// '<div pub-mod = "modules/sideBarBase.gridGroup" pub-name = "aderGrid"></div>'
				'<div class="M-formConGroup M-sidebarRadioCon">',
					'<div class="group-content">',
						'<div class="metricsCon"></div>',
					'</div>',
				'</div>'
			].join('')));

			self.create('gridFilter', grid.baseNoDate, {
				'hasSearch': true,
				'hasSubGrid': false,
				'hasExport': false,
				'hasAmount': false,
				'hasTab': false,
				'hasSelect': true,
				'reqType': 'websocket',
				// 'nameField': 'Name',
				'pager': {
					'size': 8,
					'bounds': 4,
					'showSizeTypes': false,
					'showJumper': false
				},
				'url': 'qualification/list',
				'cols': [
					{name:'_id',text:"ID", sort: true, render: 'center',align: "center"},
					{name:'UserName',text:LANG("名称"), type:'index', width: 300, render: this.renderName, align: "center"}
				],
				'list':{
					'rowSelect': true,
					'scroll_type': 'row',
					'scroll_size': 8
				},
				'target': el.find('.metricsCon')
			});

			self.uiBind(el.find('.button input'), 'click', 'eventButtonClick');

			// var config = {
			// 	'aderGrid': {
			// 		'url': 'qualification/list',
			// 		'title': ''
			// 	}
			// };

			// self.buildFromTemplate(config);
		},
		renderName: function(i, val, data, con) {
			return $('<div class="text-truncate" title="' + data.UserName + '">' + data.UserName + '</div>').width(con.width);
		},
		// 选中消息
		onChangeSelect: function(ev) {
			var c = this.getConfig();
			var data = this.$data;
			util.each(ev.param.data, function(item, idx){
				data[item._id] = {
					'id': item._id,
					'name': item[c.nameField || 'UserName']
				};
			});
			return false;
		},
		getData: function(){
			var result = [];
			var ids  = this.$.gridFilter.getSelectRowIds();
			var data = this.$data;
			util.each(ids, function(id, idx){
				if(data[id]){
					result.push(data[id]);
				}
			});
			return result;
		},
		setData: function(ids){
			this.$.gridFilter.setSelectRowIds(ids);
		},
		onOk: function(){
			var self = this;
			var data = self.getData();
			// console.log(data);
			// console.log(ader);
			self.fire('aderSelectorFilter', data);
			self.hide();
		},
		reset: function(){
			var self = this;
			return self;
		}
	});
	exports.selectAder = SelectAder;

	// 增加用户 模块
	var AddCustomer = view.container.extend({
		init: function( config ) {
			config = pubjs.conf( config, {
				'class': 'P-adminSmartMonitorAddCustomer'
			});

			this.$data = {};
			this.$selected = [];
			this.$ids = [];

			this.Super('init', arguments);
		},
		afterBuild: function(){
			var self = this;
			var el = self.getDOM();

			el.append($([
				'<div class="M-tagLabelsWrapper">',
					'<div pub-mod="@base/taglabels.listType" pub-name="type"></div>',
					'<div pub-mod="@base/taglabels.listType" pub-name="categoryId"></div>',
				'</div>',
				'<div pub-name="grid" pub-mod="admin/messageManage/grid/grid.customerGrid"></div>'
			].join('')));

			var config = {
				'type':{
					'all':true,
					'collapse': true,
					'all_label':LANG('所有'),
					'title': LANG('类型：'),
					'data': [null, LANG('代理'), LANG('直客')]
				},
				'categoryId':{
					'all':true,
					'collapse': true,
					'all_label':LANG('所有'),
					'title': LANG('版本：'),
					'data': [null, LANG('有产品版'), LANG('无产品版')]
				},
				'grid': util.extend(this.getConfig('grid') || {}, {
					// "param": {"Depth": 1}
				})
			};

			self.buildFromTemplate(config);
		},
		afterBuildTemplate: function(mod, data){
			var grid = this.$.grid;
			var filter = grid.getContainer("filter");

			var showSelected = $([
				'<label class="cur_p">',
					'<input type="checkbox" class="valign-2"/>',
					'<span>' + LANG('显示已选') + '</span>',
				'</label>'
			].join(''));
			showSelected.appendTo(filter);
			this.uiBind(showSelected, 'click', 'eventShowSelected');
		},
		onListTypeChange: function(ev){
			var grid = this.$.grid;
			switch(ev.name){
				case 'type':// 类型：1代理 2直客
					this.$Type = ev.param.type;
				break;
				case 'categoryId':// 版本：1有产品版，2无产品版
					this.$CategoryId = ev.param.type;
				break;
			}
			grid.setParam({
				'Type':this.$Type,
				'CategoryId':this.$CategoryId
			});
			grid.load();
			return false;
		},
		// 显示已选
		eventShowSelected: function(evt, elm){
			var grid = this.$.grid;
			var isChecked = $(elm).find('input').prop('checked');
			var selected = grid.getSelectRowIds();

			var ids = isChecked ? selected : [];
			grid.setParam({
				'Ids': ids
			}, true);
			grid.load();
		},
		onChangeSelect: function(ev) {
			var data = this.$data;
			util.each(ev.param.data, function(item, idx){
				data[item.UserId] = {
					'_id': item._id,
					'UserId': item.UserId,
					'Name': item.Name
				};
			});
			return false;
		},
		removeItem: function(index){
			var self = this;
			var item = util.find(self.$conditionData, index, 'index');
			if(item){
				util.each(item.modules, function(module){
					if(module){
						module.destroy();
					}
				});
				item.con.remove();
				util.remove(self.$conditionData, index, 'index');
			}

			return self;
		},
		setData: function(ids){
			if(this.get('grid')){
				this.$.grid.setSelectRowIds(ids);
			}
			return this;
		},
		getData: function(){
			var ids = this.$.grid.getSelectRowIds();
			return ids;
		},
		reset: function(){
			this.$data = {};
			this.$selected = [];
			this.$ids = [];
			// 设置好grid
			if(this.get('grid')){
				var grid = this.$.grid;
				grid.setSelectRowIds([]);
				// 重新加载数据
				grid.reload();
			}

			return this;
		}
	});
	exports.addCustomer = AddCustomer;

	// 授权 弹窗
	var AuthPop = popwin.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'title': LANG('授权客户'),
				'size': 'm',
				'view_model':{
					'name': ''
				}
			});

			this.$data = null;

			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			self.Super('afterBuild', arguments);

			var el = self.getDOM('body');
			el.append($([
				'<div class="M-formConGroup">',
					'<label class="group-label">'+LANG('监控名称：')+'</label>',
					'<div class="group-content">',
						'<span">{{name}}</span>',
					'</div>',
				'</div>',
				'<div class="M-formConGroup">',
					'<label class="group-label">'+LANG('客户：')+'</label>',
					'<div class="group-content">',
						'<span pub-name="userRadio" pub-mod="@base/common/input.radio"></span>',
						'<div class="mt10 addCustomer"></div>',
					'</div>',
				'</div>'
			].join('')));

			self.create('addCustomer', AddCustomer, {
				'target': el.find('.addCustomer').hide()
			})

			var config = {
				'userRadio': {
					'data': [
						{'text': LANG('全部'), 'id':1, 'value':'all', 'checked': true},
						{'text': LANG('自定义'), 'id':2, 'value':'custom'}
					],
					'changeEvent': true
				}
			}
			self.buildFromTemplate(config);
		},
		onRadioChange: function(ev){
			if(ev.name == 'userRadio'){
				var el = this.getDOM();
				var id = ev.param.id;
				el.find('.addCustomer').toggle(id != 1);
			}
			return false;
		},
		onOk: function(ev){
			var self = this;
			var userRadio = self.$.userRadio.getData();
			var GrantUserIds = [];
			var GrantAll = true;
			if(userRadio == 'custom'){
				GrantUserIds = self.$.addCustomer.getData();
				GrantAll = false;
			}else{
				GrantUserIds = [];
				GrantAll = true;
			}

			pubjs.mc.send('monitor/grant',{
					'_id': self.$data && self.$data._id || 0,
					'GrantAll': GrantAll,
					'GrantUserIds': GrantUserIds
				},
				self.onGrant.bind(self)
			);

			self.hide();
			return false;
		},
		onGrant: function(err, data){
			if(err) {
				pubjs.alert(err.message);
				return false;
			}
			pubjs.alert('授权成功');
			this.fire('addAuthSuccess', data);
		},
		reset: function(){
			var self = this;
			self.$data = null;
			self.$.userRadio.setData(1);
			self.$.addCustomer.reset();
			return this;
		},
		getData: function(){
			return this.$.addCustomer.getData();
		},
		setData: function(data){
			var self = this;
			if(data){
				self.reset();
				self.$data = data;
				self.vm.$.name = data.Name;
				if(data.GrantAll){
					self.$.userRadio.setData(1);
					self.$.addCustomer.setData([]);
				}else{
					self.$.userRadio.setData(2);
					self.$.addCustomer.setData(data.GrantUserIds || []);
				}
			}
			return self;
		}
	});
	exports.authPop = AuthPop;

	// 活动添加监控 弹窗
	var CreateMonitor = popwin.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'title': LANG('新建监控设置'),
				'size': 'm',
				'view_model': {

				}
			});

			this.$data = null;

			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			self.Super('afterBuild', arguments);

			var el = self.getDOM('body');
			el.append($([
				'<div pub-name="edit" pub-mod="admin/smartMonitor/action/edit.edit"></div>'
			].join('')));

			var config = {
				'edit': {
					'hasFootBtn': false
				}
			}
			self.buildFromTemplate(config);
		},
		onOk: function(ev){
			var self = this;
			if(self.get('edit')){
				self.get('edit').save('afterPopSave');
			}
			self.hide();
			return false;
		},
		reset: function(){
			var self = this;
			if(self.get('edit')){
				self.get('edit').reset();
			}
			return this;
		}
	});
	exports.createMonitor = CreateMonitor;

	// 设置邮箱的弹窗
	var EmailsPop = popwin.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'title': LANG('请设置邮箱'),
				'size': 'm',
				'view_model':{
					'emails': ''
				}
			});

			this.$data = null;
			this.$error = false;

			this.Super('init', arguments);
		},
		afterBuild:function(){
			var self = this;
			self.Super('afterBuild', arguments);

			var el = self.getDOM('body');
			self.$textarea = $([
				'<div class="mb10 text-muted">'+LANG('多个邮箱使用 ; 或换行隔开')+'</div>',
				'<textarea class="h200 w100pct mr10" ms-duplex="emails" ></textarea>'
			].join('')).appendTo(el);

		},
		onOk: function(ev){
			var self = this;
			var data = self.getData();

			if(self.$error){
				pubjs.alert(LANG('请输入合法的邮箱！'), function(){
					self.$textarea.focus();
				});
				return false;
			}

			if(data.length > 20){
				pubjs.alert(LANG('最多不超过20个邮箱！'), function(){
					self.$textarea.focus();
				});
				return false;
			}

			pubjs.mc.send('monitor/setEmails', {
					'Emails': data
				},
				self.onSetEmails.bind(self)
			);

			self.hide();
			return false;
		},
		onSetEmails: function(err, data){
			if(err) {
				pubjs.alert(err.message);
				return false;
			}
			pubjs.alert('设置成功');
			this.fire('setEmailsSuccess', data);
		},
		load: function(){
			var self = this;
			self.showLoading();
			pubjs.mc.send('monitor/getEmails', {}, self.onLoad.bind(self));
			return self;
		},
		onLoad: function(err, data){
			if(err) {
				pubjs.alert(err.message);
				return false;
			}
			this.setData(data || {});
			this.hideLoading();
		},
		reset: function(){
			var self = this;
			self.$error = false;
			self.vm.reset();
			return self;
		},
		getData: function(){
			var self = this;
			self.$error = false; // 还原错误标记
			var vm = self.vm.$;
			// 重新处理一下Emails
			var Emails = [];
			util.each(vm['emails'].replace(/(\n)+|(\r\n)+|(；)+|(;)/g, '\n').split('\n'), function(item){
				var email = util.trim(item);
				if(email){
					if(util.isEmail(email)){
						Emails.push(email);
					}else{
						self.$error = true;
					}
				}
			});
			return util.unique(Emails);
		},
		setData: function(data){
			var self = this;
			var vm = self.vm.$;
			if(data){
				vm.emails = data.Emails && data.Emails.join(';\n') || '';
			}
			return self;
		}
	});

	exports.emailsPop = EmailsPop;
});